(function($, doc) {
	$.init();
	var userinfo = app.getState() || {};
	var uid=userinfo.user_id;
	
	$.plusReady(function() {
		//doc.querySelector(".set_uid").innerHTML='UID:'+userinfo.user_id;
		
		doc.getElementById("nick_name").innerHTML  = '：' + userinfo.nickname;
		doc.getElementById("user_name").innerHTML  = '：' + userinfo.user_id;
		doc.getElementById("user_score").innerHTML = '：' + userinfo.score;
			
        if(userinfo.headimgurl && userinfo.headimgurl.indexOf('Uploads') !== -1){
	    	//doc.getElementById('headimg').src=serverurl + 'Uploads/avatar/' + userinfo.user_id + '.jpg';
	        if(userinfo.headimgurl.indexOf(upurl+'Uploads') !== -1){
				doc.getElementById('headimg').src=userinfo.headimgurl;
			}
			else{
				doc.getElementById('headimg').src=upurl+userinfo.headimgurl;
			}
        }
	    else{
	    	doc.getElementById('headimg').src='img/logo.png';
	    }
	    
	    doc.getElementById('nike').innerHTML=userinfo.nickname;
//	    doc.getElementById('nickname').innerHTML=userinfo.nickname;
	    
	    
	    var langsets = localStorage.getItem('defaultLan');
	    if(langsets=='en'){
	    	doc.getElementById('now_langage').innerHTML='English';
	    }
	    if(langsets=='zh'){
	    	doc.getElementById('now_langage').innerHTML='中文';
	    }
	    
		 //退出操作******************
		document.getElementById('out_login').addEventListener('tap', function() {
			app.setState({});
			localStorage.removeItem('$token');
			mui.getJSON(apiurl + "Login/logout/", null, function(data) {
				plus.runtime.restart(); 
			});
			//app.out();
		}, false);
		
		doc.getElementById('nikename').addEventListener('tap', function() {
			  //打开昵称页
			  mui.openWindow({
			    id:'change_name.html',
			    url:'pages/setting/change_name.html',
			    show: {
					aniShow: 'pop-in'
				},
				waiting: {
					autoShow: false
				}
			  });
		}, false);

		doc.getElementById('card').addEventListener('tap', function() {
			 //打开支付方式管理页
			  mui.openWindow({
			    id:'payment_method.html',
			    url:'pages/setting/payment_method.html',
			    show: {
					aniShow: 'pop-in'
				},
				waiting: {
					autoShow: false
				}
			  });
			/*
			  //打开我的银行卡页
			  mui.openWindow({
			    id:'addcard.html',
			    url:'pages/setting/addcard.html',
			    show: {
					aniShow: 'pop-in'
				},
				waiting: {
					autoShow: false
				}
			  });*/
		}, false);

		doc.getElementById('set_loginpwd').addEventListener('tap', function() {
			  //打开登录密码页
			  mui.openWindow({
			    id:'loginpwd.html',
			    url:'pages/setting/loginpwd.html',
			    show: {
					aniShow: 'pop-in'
				},
				waiting: {
					autoShow: false
				}
			  });
		}, false);
		
		doc.getElementById('set_trade_pwd').addEventListener('tap', function() {
			  //打开支付密码页
			  mui.openWindow({
			    id:'paymentpwd.html',
			    url:'pages/setting/paymentpwd.html',
			    show: {
					aniShow: 'pop-in'
				},
				waiting: {
					autoShow: false
				}
			  });
		}, false);
		
		doc.getElementById('change-phone').addEventListener('tap', function() {
			  //打开修改手机号
			  mui.openWindow({
			    id:'change-phone.html',
			    url:'pages/setting/change-phone.html',
			    show: {
					aniShow: 'pop-in'
				},
				waiting: {
					autoShow: false
				}
			  });
		}, false);
		
		doc.getElementById('qr_code').addEventListener('tap', function() {
			  //打开分享页
			  mui.openWindow({
			    id:'share.html',
			    url:'pages/setting/share.html',
			    show: {
					aniShow: 'pop-in'
				},
				waiting: {
					autoShow: false
				}
			  });
		}, false);
		
		doc.getElementById('about').addEventListener('tap', function() {
			  //打开关于页
			  mui.openWindow({
			    id:'about.html',
			    url:'pages/setting/about.html',
			    show: {
					aniShow: 'pop-in'
				},
				waiting: {
					autoShow: false
				}
			  });
		}, false);
		
		doc.getElementById('notice').addEventListener('tap', function() {
			  //打开公告页
			  mui.openWindow({
			    id:'notice.html',
			    url:'pages/setting/notice.html',
			    show: {
					autoShow:false
				},
				waiting:{
			       autoShow:true,//自动显示等待框，默认为true
			       title:'正在加载...'//等待对话框上显示的提示内容
			   }
			  });
		}, false);
		
		doc.getElementById('news').addEventListener('tap', function() {
			  //打开个人消息页
			  mui.openWindow({
			    id:'news.html',
			    url:'pages/setting/news.html',
			    show: {
					aniShow: 'pop-in'
				},
				waiting: {
					autoShow: false
				}
			  });
		}, false);
		
		doc.getElementById('suggest').addEventListener('tap', function() {
			  //打开投诉建议页
			  mui.openWindow({
			    id:'suggest.html',
			    url:'pages/setting/suggest.html',
			    show: {
					aniShow: 'pop-in'
				},
				waiting: {
					autoShow: false
				}
			  });
		}, false);
		
		
		//点击我的店铺
		doc.getElementById('mystore').addEventListener('tap', function() {
			mui.ajax({
				url: apiurl + "Store/get_store/",
				data: {'user_id':userinfo.user_id,'_token':userinfo.token},
				async: true,
				dataType: 'json',
				crossDomain: true, //强制使用5+跨域
				type: 'get',
				timeout: 10000,
				success: function(res) {
					console.log(JSON.stringify(res));
					if(res.status ==-3){
						mui.toast(res.msg);
						app.out();
						return false;
					}
					
					// 请求成功
					if(res.status < 1) {
						//打开店铺中心
						mui.openWindow({
						    id:'shop.html',
						    url:'pages/setting/shop/shop.html',
						    show: {
								aniShow: 'pop-in'
							},
							waiting: {
								autoShow: false
							}
						});
			  
					} else {
						//打开申请店铺
						mui.openWindow({
						    id:'shop-apply.html',
						    url:'pages/setting/shop/shop-apply.html',
						    show: {
								aniShow: 'pop-in'
							},
							waiting: {
								autoShow: false
							}
						});
					}
				},
				error: function(xhr, type, errorThrown) {
					//console.log(JSON.stringify(xhr));
					//console.log(JSON.stringify(type));
					//console.log(JSON.stringify(errorThrown));
					mui.toast('操作失败！');
				}
			});
			  
		}, false);

		doc.getElementById('myorder').addEventListener('tap', function() {
			//打开我的订单页
			mui.openWindow({
				id: 'my-order.html',
				url: 'pages/setting/shop/my-order.html',
				show: {
					autoShow: false
				},
				waiting: {
					autoShow: true,
					title: '正在加载...'
				} 
			});
		})
		
		
		doc.getElementById('address').addEventListener('tap', function() {
			//打开地址管理页
			mui.openWindow({
				id: 'address.html',
				url: 'pages/setting/address.html',
				show: {
					autoShow: false
				},
				waiting: {
					autoShow: true,
					title: '正在加载...'
				}
			});
		})
		
		
		//点击多语言
		doc.getElementById('change_lang').addEventListener('tap', function() {
			doc.getElementById('lang-zz').style.display='block';
		})
		doc.getElementById('quxiao').addEventListener('tap', function() {
			doc.getElementById('lang-zz').style.display='none';
		})
		doc.getElementById('contain').addEventListener('tap', function() {
			if(!doc.querySelector('.lang-main .langbox .mui-icon-checkmarkempty')){
				doc.getElementById('lang-zz').style.display='none';
			}
			else{
				var selected=doc.querySelector('.lang-main .langbox .mui-icon-checkmarkempty');
				var sid=selected.getAttribute('id');
				var langset = localStorage.getItem('defaultLan');
				if(sid=='zh_lang' && langset=='zh'){
					doc.getElementById('lang-zz').style.display='none';
					return;
				}
			    if(sid=='en_lang' && langset=='en'){
					doc.getElementById('lang-zz').style.display='none';
					return ;
				}
			    if(sid=='zh_lang' && langset!='zh'){
					localStorage.setItem('defaultLan', 'zh');
					mui.alert('设置成功！');
					plus.runtime.restart();
				}
				if(sid=='en_lang' && langset!='en'){
					localStorage.setItem('defaultLan', 'en');
					mui.alert('设置成功！');
					plus.runtime.restart();
				}
			}
		})
		
		mui("#lang-zz").on('tap','.lang-main .langbox',function(){
			var type=this.getAttribute('data-lang');
			var span_arr = document.querySelectorAll('#lang-zz .lang-main .langbox span');
			mui.each(span_arr,function(index,item){
			   item.className='mui-icon';
			});
			doc.getElementById(type+'_lang').className='mui-icon mui-icon-checkmarkempty';
		})
		
		window.addEventListener('refresh_nickname',function(event){
		  	userinfo = app.getState() || {};
		  	doc.getElementById('nike').innerHTML=userinfo.nickname;
		  	doc.getElementById('nickname').innerHTML=userinfo.nickname;
		});


		mui('body').on('tap', '.mui-popover-action li>a', function() {
			var a = this,
				parent;
			//根据点击按钮，反推当前是哪个actionsheet
			for (parent = a.parentNode; parent != document.body; parent = parent.parentNode) {
				if (parent.classList.contains('mui-popover-action')) {
					break;
				}
			}
			//关闭actionsheet
			mui('#' + parent.id).popover('toggle');
			if(a.getAttribute('id')=='xiangce'){
				//从相册选择
				galleryImg();
				return false;
			}
			if(a.getAttribute('id')=='paizao'){
				//拍照
				getImage();
				return false;
			}
		})
		
		//拍照
		function getImage() {
			var c = plus.camera.getCamera();
			c.captureImage(function(e) {
				plus.io.resolveLocalFileSystemURL(e, function(entry) {
					var s = entry.toLocalURL() + "?version=" + new Date().getTime();
					console.log(s);
					document.getElementById("headimg").src = s;
					uploadImg(s);
					//变更大图预览的src
					//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
					document.querySelector("#__mui-imageview__group .mui-slider-item img").src = s + "?version=" + new Date().getTime();
				}, function(e) {
					console.log("读取拍照文件错误：" + e.message);
				});
			}, function(s) {
				console.log("error" + s);
			}, {
				filename: "_doc/head.jpg"
			})
		}
		
		
		//相册
		function galleryImg() {
			plus.gallery.pick(function(a) {
				plus.io.resolveLocalFileSystemURL(a, function(entry) {
					plus.io.resolveLocalFileSystemURL("_doc/", function(root) {
						root.getFile("head.jpg", {}, function(file) {
							//文件已存在
							file.remove(function() {
								console.log("file remove success");
								entry.copyTo(root, 'head.jpg', function(e) {
										var e = e.fullPath + "?version=" + new Date().getTime();
										document.getElementById("headimg").src = e;
										uploadImg(e);
										//变更大图预览的src
										//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
										document.querySelector("#__mui-imageview__group .mui-slider-item img").src = e + "?version=" + new Date().getTime();;
									},
									function(e) {
										console.log('copy image fail:' + e.message);
									});
							}, function() {
								console.log("delete image fail:" + e.message);
							});
						}, function() {
							//文件不存在
							entry.copyTo(root, 'head.jpg', function(e) {
									var path = e.fullPath + "?version=" + new Date().getTime();
									document.getElementById("headimg").src = path;
									//document.getElementById("head-img1").src = path;
									//变更大图预览的src
									//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
									document.querySelector("#__mui-imageview__group .mui-slider-item img").src = path;
								},
								function(e) {
									console.log('copy image fail:' + e.message);
								});
						});
					}, function(e) {
						console.log("get _www folder fail");
					})
				}, function(e) {
					console.log("读取拍照文件错误：" + e.message);
				});
			}, function(a) {}, {
				filter: "image"
			})
		}


		function uploadImg(path) {
			var img = new Image();
			img.src = path;
			img.onload = function() {
				var that = this;
				//生成比例 
				var w = that.width,
					h = that.height,
					scale = w / h;
				w = 480 || w; //480  你想压缩到多大
				h = w / scale;
		
				//生成canvas
				var canvas = document.createElement('canvas');
				var ctx = canvas.getContext('2d');
				canvas.setAttribute('width', w);
				canvas.setAttribute('height', h);
				ctx.drawImage(that, 0, 0, w, h);
				var base64 = canvas.toDataURL('image/jpeg', 1 || 0.8); //1z 表示图片质量，越低越模糊。	 
				console.log(base64);
				//base64 = base64.replace('data:image/jpeg;base64,', '');
				mui.post(uploadurl, {
					file: base64,
					uid: uid,
					path : path,
					name : 'avatar',
					pid : uid
				}, function(res) {
					console.log(JSON.stringify(res));
					if(res.status > 0) {
						//document.getElementById("headimg").src = serverurl + 'Uploads/avatar/' + userinfo.user_id + '.jpg';
	                    var user_path=res.url;
					    mui.post(apiurl + "User/setheader/",{
					    	uid: uid,
							path : user_path,
							_token:userinfo.token
					    },function(data){
					    	if(data.status ==-3){
								mui.toast(data.msg);
								app.out();
								return false;
							}
					    	if(data.status>0){
					    		mui.toast('更换头像成功');
					    		userinfo.headimgurl = user_path;
	                    		app.setState(userinfo);
	                    		mui.fire(plus.webview.getWebviewById('index.html'),'refresh_headimg');
					    	}
					    });
					
					}
				},'json');
		
			}
		}
		
		
	})
	
}(mui, document));